function coords = mainLoop(v, file)
% Aarde main loop functie

global number
global points
global k

if isequal(size(number),[0 0]);
    number = size(v,2);
end

if isequal(size(points),[0 0]);
    points = 0;
end

knowns = size(v,2)-sum(v==0)-sum(v==255);
if(knowns<3 || ~isequal(size(find(v==0)),[1 1]))
    return;
end

if points==0;
    k = [0; 0];
    global d
    d = v;
    fprintf(file,'%i\n', number);
    fprintf(file,'%f %f\n', k(1,1), k(2,1));
    scatter(k(1,1), k(2,1),'blue');
elseif points==1;
    global d
    d(2,:) = v;
    % Error correctie
    if(~isequal(d(1,2),255))
        k(:,2) = [d(1,2); 0];
    elseif(~isequal(d(2,1),255))
        k(:,2) = [d(2,1); 0];
    else
        error('Initialization failed');
    end
    fprintf(file,'%f %f\n', k(1,2), k(2,2));
    scatter(k(1,2), k(2,2),'blue');
elseif points==2;
    global d
    d(3,:) = v;
    % Error correctie
    if(isequal(d(1,2),255))
        if(~isequal(d(2,1),255))
            d(1,2) = d(2,1);
        else
            error('Initialization failed');
        end
    end
    if(isequal(d(1,3),255))
        if(~isequal(d(3,1),255))
            d(1,3) = d(3,1);
        else
            error('Initialization failed');
        end
    end
    if(isequal(d(2,3),255))
        if(~isequal(d(3,2),255))
            d(2,3) = d(3,2);
        else
            error('Initialization failed');
        end
    end
    k(:,3) = [((d(1,3)^2-d(2,3)^2+d(1,2)^2)/(2*d(1,2)));
             sqrt(d(1,3)^2-((d(1,3)^2-d(2,3)^2+d(1,2)^2)/(2*d(1,2)))^2)];
    if k(2,3)<0.0001&&k(2,3)>-0.0001;
        k(2,3) = 0.0001;
    end
    fprintf(file,'%f %f\n', k(1,3), k(2,3));
    scatter(k(1,3), k(2,3),'blue');
elseif points<number;
    % Error correctie
    global d
    d(points+1,:) = v;
    broken = find(v(1,1:points+1)==255);
    if(~isequal(size(broken),[1 0]))
        v(1,broken) = d(broken,points+1);
    end
    k(:,points+1) = zeros(2,1);
    k = calculation(k,v(1,1:points+1),'blue',file);
    if(isequal(k,[]))
        error('Initialization failed');
    end
else
    k = calculation(k,v,'red',file);
end

points = points + 1;
coords = k;

end

